<template>
    <div class="app-container">
        <div class="header">
            <el-button type="primary" @click="dialogSaveImagesForm = true" size="mini">添加</el-button>
            <el-input style="width: 300px; margin-left: 100px;" size="mini" placeholder="输入关键字搜索" @change="imagesSearch"
                @input="checkVal" v-model="imagesListForm.memo">
                <i slot="suffix" class="el-icon-search"></i>
            </el-input>
        </div>



        <!-- 添加素材弹出框 -->
        <el-dialog title="添加素材" :visible.sync="dialogSaveImagesForm" :close-on-click-modal="false"
            @close="closeSaveSourceForm">
            <el-form ref="saveImagesForm" :model="saveImagesForm" label-width="100px" :rules="saveRules">
                <el-form-item label="上传图片" prop="file">
                    <el-upload class="upload-demo" action="#" :before-upload="beforeUpload" :on-change="handleChange"
                        :before-remove="beforeRemove" :limit="1" accept=".jpg, .png, .jpeg" :on-exceed="handleExceed"
                        :on-progress="handleProgress" :auto-upload="false" :file-list="fileList">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过10MB</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="图片名字" prop="imagesName">
                    <el-input v-model="saveImagesForm.imagesName" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="saveSource" :loading="loading">提交</el-button>
                    <el-button @click="closeSaveSourceForm">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 素材信息列表 -->
        <div class="content">
            <el-table :data="imagesList" style="width: 100%;" stripe
                :default-sort="{ prop: 'date', order: 'descending' }">
                <el-table-column label="素材信息">
                    <el-table-column label="名称" width="180" prop="name">
                        <template slot-scope="scope">
                            <div>{{ scope.row.name }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="图片地址" width="180" prop="url">
                        <template slot-scope="scope">
                            <el-image style="width: 100px; height: 100px" :src="scope.row.url" fit="fit"></el-image>
                        </template>
                    </el-table-column>
                </el-table-column>

                <el-table-column label="添加">
                    <el-table-column label="添加者">
                        <template slot-scope="scope">
                            <div>{{ scope.row.saveAdmin }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作时间" width="180" sortable prop="date">
                        <template slot-scope="scope">
                            <i class="el-icon-time" v-if="scope.row.saveTime != null"></i>
                            <span style="margin-left: 10px">{{ scope.row.saveTime }}</span>
                        </template>
                    </el-table-column>
                </el-table-column>

                <el-table-column label="删除">
                    <el-table-column label="删除者">
                        <template slot-scope="scope">
                            <div>{{ scope.row.removeAdmin }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="删除理由">
                        <template slot-scope="scope">
                            <div>{{ scope.row.removeMemo }}</div>
                        </template>
                    </el-table-column>
                </el-table-column>

                <el-table-column label="操作">
                    <el-table-column label="删除">
                        <template slot-scope="scope">
                            <el-button type="danger" circle icon="el-icon-delete"
                                @click="delImages(scope.row.id)"></el-button>
                            <!-- @click="delAdmin(scope.row.id)" -->
                        </template>
                    </el-table-column>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="imagesListSizeChange" @current-change="imagesListCurrentChange"
                :page-size="imagesListForm.size" :page-sizes="[10, 20, 30]" layout="total, sizes, prev, pager, next"
                :total="imagesListTotal" style="margin-top: 20px;">
            </el-pagination>
        </div>
    </div>
</template>

<script>
import utils from '@/utils/checkLogin'
import { Message } from 'element-ui'
import { getImagesList, deleteImages, saveImages } from '../../api/api'
import { jwtDecode } from 'jwt-decode'
export default {
    data() {
        const uploadFile = (rule, value, callback) => {
            if (this.fileList.length < 1) {
                callback(new Error('请上传图片'))
            } else {
                callback()
            }
        }
        return {
            loading: false,
            dialogSaveImagesForm: false,
            sourceForm: {},
            fileList: [],
            saveImagesForm: {
                file: '',
                imagesName: ''
            },
            imagesList: [],
            imagesListForm: {
                page: 1,
                size: 10,
                meno: ''
            },
            imagesListTotal: 0,
            saveRules: {
                imagesName: [
                    { required: true, message: '请填写名称', trigger: 'change' }
                ],
                file: [
                    { required: true, validator: uploadFile, message: '请上传图片', trigger: 'change' },
                ]
            },
        }
    },
    methods: {
        closeSaveSourceForm() {
            this.dialogSaveImagesForm = false
            this.$nextTick(() => {
                // 添加成功时，置空 form 表单
                this.$refs.saveImagesForm.resetFields()
                this.fileList = []
            })
        },
        beforeUpload(file) {
            // let types = ['image/jpeg', 'image/jpg', 'image/png']
            // const isImage = file.types.includes(types);
            // // const imgFormat = file.raw.type === "image/jpeg" || file.raw.type === "image/png" || file.raw.type === "image/jpg"
            // const isLt10M = file.raw.size / 1024 / 1024 < 10
            // if (!isLt10M) {
            //     this.$message.warning("上传图片大小不能超过 10M!")
            //     // return false
            // }
            // if (!isImage) {
            //     this.$message.warning("上传图片格式只能是jpg、jpeg、png!")
            //     // return false
            // }
            // // this.fileList = fileList
            // return isImage && isLt10M
            console.log('beforeUpload');
        },
        // 文件超出个数限制时的钩子
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${fileList.length} 个文件`);
        },
        // 删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除。
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        // 文件上传时的钩子
        handleProgress(event, file, fileList) {
            console.log('handleProgress');
            this.saveImagesForm.file = file.name
        },
        handleChange(file, fileList) {
            console.log('handleChange');
            // this.fileList = fileList
            const imgFormat = file.raw.type === "image/jpeg" || file.raw.type === "image/png" || file.raw.type === "image/jpg"
            const isLt10M = file.raw.size / 1024 / 1024 < 10
            if (!isLt10M) {
                this.$message.warning("上传图片大小不能超过 10M!")
                this.fileList = []
                return false
            } else if (!imgFormat) {
                this.$message.warning("上传图片格式只能是jpg、jpeg、png!")
                this.fileList = []
                return false
            } else {
                this.fileList = fileList
            }
        },
        // 点击确定，上传
        saveSource() {
            const param = new FormData()
            this.fileList.forEach((val, index) => {
                param.append('file', val.raw)
            })
            // param.append('imagesName', this.saveImagesForm.imagesName)
            // this.saveImagesForm.file = param
            param.append('imagesName', this.saveImagesForm.imagesName)

            this.$refs.saveImagesForm.validate(valid => {
                if (!valid) {
                    Message({
                        message: '请检查表单！',
                        type: 'warning',
                        duration: 2000
                    })
                    return false
                } else {
                    saveImages(param).then((res) => {
                        if (res.code == 200) {
                            Message({
                                message: '添加成功',
                                type: 'success',
                                duration: 3000
                            })
                            this.loading = true
                            console.log('添加素材', res)
                            this.getImagesListData()
                            setTimeout(() => {
                                this.loading = false
                                this.dialogSaveImagesForm = false
                                this.$nextTick(() => {
                                    // 添加成功时，置空 form 表单
                                    this.$refs.saveImagesForm.resetFields()
                                    this.fileList = []
                                })
                            }, 2000)
                        }
                    })
                }
            })
        },
        getImagesListData() {
            getImagesList(this.imagesListForm).then((res) => {
                if (res.code == 200) {
                    console.log('素材列表', res)
                    this.imagesList = res.data
                    this.imagesListTotal = res.total
                }
            })
        },
        // 素材列表，当每页条数切换时
        imagesListSizeChange(e) {
            console.log(e);
            this.imagesListForm.size = e
            console.log(JSON.stringify(this.imagesListForm));
            this.getImagesListData()
        },
        // 素材列表，当当前页码改变时
        imagesListCurrentChange(e) {
            console.log(e);
            this.imagesListForm.page = e
            console.log(JSON.stringify(this.imagesListForm));
            this.getImagesListData()
        },
        // 搜索
        imagesSearch() {
            this.getImagesListData()
        },
        // 如果搜索框的值为空，刷新一下商品列表
        checkVal() {
            if (this.imagesListForm.memo == '') {
                this.getImagesListData()
            }
        },
        delImages(imagesId) {
            console.log(imagesId);
            let obj = {
                imagesId,
            }
            this.$prompt('请输入删除理由', '删除提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(({ value }) => {
                obj.removeMemo = value
                deleteImages(obj).then((res) => {
                    console.log('删除素材', res);
                    if (res.code == 200) {
                        console.log('删除成功', res);
                        this.$message({
                            type: 'success',
                            message: '删除成功',
                            duration: 3000
                        })
                        this.getImagesListData()
                    } else {
                        this.$message({
                            type: 'error',
                            message: '删除失败',
                            duration: 3000
                        })
                    }
                })

            }).catch(() => {
            })
        }
    },
    created() {
        utils.checkLogin()
        this.getImagesListData()
    }
}
</script>

<style lang="less" scoped>
.app-container {
    padding: 40px;

    .header {
        // justify-content: space-evenly;
        align-items: center;
        display: flex;
        margin-bottom: 20px;

        .el-icon-search {
            cursor: pointer;
            margin-right: 4px;
            margin-top: 8px;
            // border: 1px solid red;
        }
    }

    .content {
        text-align: center;
    }
}
</style>